<template>
  <view class="uni-pa-4 bg-white">
    <view class="uni-pa-4">
      <uni-file-picker ref="files" v-model="imageValue" @select="select" @deletselecte="deleteImg" limit="1" title="最多選擇1個視頻"
        file-mediatype="video" mode="grid"></uni-file-picker>
    </view>
    <input class="uni-py-4" type="text" v-model="body.title" placeholder="填寫標題會有更多贊哦~">
    <textarea class="uni-py-4" v-model="body.content" :maxlength="-1" placeholder="添加正文" auto-height />
    <view class="uni-list">
      <radio-group @change="radioChange">
        <label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in radioList" :key="item.value">
          <view>
            <radio :value="item.value" :checked="item.value == body.leixing" />
            {{ item.label }}
          </view>
        </label>
      </radio-group>
    </view>
    <view>
      <text v-for="(item, index) in body.topic" :key="index" class="uni-px-2 text-blue-900">#{{ item }}</text>
    </view>
    <view class="uni-mt-8 uni-mb-8">
      <button class="uni-mr-4" @click="openPopup" type="default" size="mini"># 话题</button>
      <!-- <button type="default" size="mini">@ 用户</button> -->
    </view>
    <uni-goods-nav @click="saveToDraft" @buttonClick="toRelease" :fill="true" :options="options"
      :button-group="customButtonGroup" />
    <!-- 普通弹窗 -->
    <uni-popup ref="popup" type="bottom">
      <view class="bg-white">
        <uni-section title="輸入話題" subTitle=" " type="line" padding>
          <uni-easyinput confirm v-model="topicValue" focus placeholder="請輸入内容" @confirm="pushTopic"></uni-easyinput>
        </uni-section>
        <uni-group>
          <view @click="selectTopic(item.name)" v-for="item in topic" :key="item.id"
            class="flex justify-between text-gray-500 uni-my-2">
            <text>#{{ item.name }}</text>
            <text>{{ item.browse }}次瀏覽</text>
          </view>
        </uni-group>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import {
  httpNoteRelease,
  httpTopicTop,
  httpRadioList
} from '@/utils/api.js'
import { baseURL } from '@/utils/base.js'
export default {
  data() {
    return {
      body: {
        userId: '',
        title: '',
        content: '',
        carousel: [],
        topic: [],
        leixing: ''
      },
      imageValue: [],
      topicValue: '',
      options: [{
        icon: 'compose',
        text: '存草稿'
      }],
      customButtonGroup: [{
        text: '發表筆記',
        backgroundColor: '#e30e33',
        color: '#fff '
      }],
      topic: [],
      radioList: [{ label: '美食', value: '1', }, { label: '生活', value: '2' }, { label: '寻根', value: '3' }, { label: '饮食', value: '4' }, { label: '政策', value: '5' }],
      current: ''
    }
  },
  onLoad() {
    // 获取用户id，uniapp自动调用
    const user = getApp().globalData.user
    if (user) {
      this.body.userId = user.userId || user.id
    } else {
      console.log("請登錄")
    }
  },
  methods: {
    async getRadioList() {

      const { code, data } = await httpRadioList()
      if (code === 200) {
        this.radioList = data.map(item => {
          return {
            label: item.t_name,
            value: item.t_type,
          }
        })
        this.radioList.shift()
      }
    },
    radioChange(evt) {
      for (let i = 0; i < this.radioList.length; i++) {
        if (this.radioList[i].value === evt.detail.value) {
          this.current = i;
          this.body.leixing = this.radioList[i].value
          break;
        }
      }
    },
    // 选择话题
    selectTopic(e) {
      this.$refs.popup.close()
      this.body.topic.push(e)
    },
    // 保存草稿
    async saveToDraft() {
      const draft = {
        ...this.body,
        carousel: JSON.stringify(this.body.carousel),
        topic: JSON.stringify(this.body.topic)
      }
      // 存储到本地
      uni.setStorage({
        key: 'draft_key',
        data: draft,
        success: () => {
          uni.showToast({
            title: '保存成功',
            duration: 2000,
            complete: () => {
              // 清空内容
              this.body = {
                userId: this.body.userId,
                title: '',
                content: '',
                carousel: [],
                topic: [],
                type: ''
              }
              this.$refs.files.clearFiles()
              setTimeout(() => {
                uni.switchTab({
                  url: '/pages/index/index'
                })
              }, 1000)
            }
          })
        }
      })
    },
    // 弹出框
    async openPopup(e) {
      this.$refs.popup.open('top')
      const { code, data } = await httpTopicTop()
      if (code === 200) this.topic = data
    },
    // 输入话题
    pushTopic(e) {
      this.body.topic.push(e)
      this.topicValue = ''
      this.$refs.popup.close()
    },
    // 获取上传状态
    select(e) {
	  this.body.title = e.tempFiles[0].name.slice(0, -4)
      const tempFilePaths = e.tempFilePaths //e是获取的文件源
      uni.uploadFile({
        url: baseURL + '/file/upload', //上传文件的后端接口
		
        filePath: tempFilePaths[0],
        name: 'file',
        success: res => {
          this.body.carousel = [JSON.parse(res.data).data.url]
        }
      })
    },
    deleteImg(e) {
      // this.body.carousel = this.body.carousel.filter(item => item != e.tempFilePath)
      this.body.carousel.pop()
    },
    // 发布
    async toRelease() {
      // 校验输入内容
      if (this.body.title == '') {
        uni.showToast({
          title: '請輸入標題！',
          icon: 'none'
        })
        return false
      } else if (this.body.leixing == '') {
        uni.showToast({
          title: '請選擇視頻分類！',
          icon: 'none'
        })
        return false
      }
      const {
        code
      } = await httpNoteRelease({
        ...this.body,
        carousel: JSON.stringify(this.body.carousel),
        topic: JSON.stringify(this.body.topic),
      })
      if (code === 200) {
        uni.showToast({
          title: '發佈成功',
          duration: 2000,
          complete: () => {
            // 清空内容
            this.body = {
              userId: this.body.userId,
              title: '',
              content: '',
              carousel: [],
              leixing: '',
              topic: [],
            }
            this.$refs.files.clearFiles()
            setTimeout(() => {
              uni.switchTab({
                url: '/pages/index/index'
              })
            }, 1000)
          }
        })
      }
    }
  },
  mounted() {
    this.getRadioList()
    // this.checkChildHeight();

  },
}
</script>

<style lang="scss" scoped>
// 底部栏
::v-deep .uni-tab__cart-box {
  z-index: 0 !important;
}

::v-deep .file-picker__box-content {
  background: #fff !important;
}

::v-deep .uni-list {
  uni-radio-group {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
	flex-wrap: wrap;
	.uni-list-cell{
		flex: 0 0 33.33%;
		margin-bottom: 5px;
	}
  }
}
</style>